#include "music.h"

#include <QIcon>
#include <QFont>
#include <QUrl>
#include <QDebug>
#include <algorithm>
#include <QTime>

music::music(QWidget *parent)
    : Widget_class(parent)
    , isPlaying(false)
    , currentPosition(0)
    , totalDuration(0)
    , currentLyricIndex(-1)
{
    // 创建播放定时器
    playTimer = new QTimer(this);
    playTimer->setInterval(100);  // 每100毫秒更新一次
    setupUI();

    network = new music_json(this);

    mediaPlayer = new QMediaPlayer(this);
    musiclist = new QMediaPlaylist(this);
    mediaPlayer->setPlaylist(musiclist);

    // 初始化歌曲映射
    songMap["洗牌"] = "2721721636";
    songMap["深海少女"] = "469073360";
    songMap["十年"] = "1467536356";
    songMap["午夜之门"] = "2006449765";
    songMap["得吃小曲"] = "2747313314";

    setupConnections();  // 连接信号与槽
}

music::~music()
{
    if (playTimer->isActive()) {
        playTimer->stop();
    }
}

void music::setupUI()
{
    // 创建组件
    iconLabel = new QLabel(this);
    lyricsLabel = new QLabel(this);
    progressBar = new QProgressBar(this);
    prevButton = new QPushButton(this);
    playButton = new QPushButton(this);
    nextButton = new QPushButton(this);

    // 设置图标
    iconLabel->setPixmap(QPixmap(":/音乐"));
    iconLabel->setScaledContents(true);
    iconLabel->setAlignment(Qt::AlignCenter);
    iconLabel->setStyleSheet("QLabel { font-size: 20px; }");

    // 设置歌词显示
    lyricsLabel->setText("等待加载歌词...");
    lyricsLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    lyricsLabel->setWordWrap(true);
    lyricsLabel->setStyleSheet("QLabel { background-color: #f8f8f8; border: 1px solid #ddd; padding: 5px; font-size: 10px; }");

    // 设置进度条 - 更紧凑
    progressBar->setRange(0, 100); // 初始范围，加载歌曲后会更新
    progressBar->setValue(0);
    progressBar->setTextVisible(true); // 小尺寸下隐藏文字
    progressBar->setFixedHeight(12);
    // 设置进度条样式
    progressBar->setStyleSheet(
        "QProgressBar {"
        "    border: 1px solid #87CEEB;"
        "    border-radius: 6px;"
        "    background-color: #E6F7FF;"
        "    text-align: center;"
        "    color: #2E8B57;"
        "    font-size: 10px;"
        "}"
        "QProgressBar::chunk {"
        "    background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "    stop:0 #1E90FF, stop:0.5 #00BFFF, stop:1 #87CEFA);"
        "    border-radius: 5px;"
        "    border: 1px solid #4682B4;"
        "}");
    // 设置按钮图标
    prevButton->setIcon(QIcon(":/后退"));
    nextButton->setIcon(QIcon(":/前进"));
    playButton->setIcon(QIcon(":/开始"));  // 初始为播放图标

    // 设置图标大小
    QSize iconSize(24, 24);
    prevButton->setIconSize(iconSize);
    playButton->setIconSize(QSize(30,30));
    nextButton->setIconSize(iconSize);

    // 设置透明样式
    QString transparentStyle =
        "QPushButton {"
        "    background: transparent;"
        "    border: none;"
        "    outline: none;"
        "}"
        "QPushButton:hover {"
        "    background-color: rgba(255, 255, 255, 100);"  // 悬停效果
        "    border-radius: 3px;"
        "}"
        "QPushButton:pressed {"
        "    background-color: rgba(255, 255, 255, 150);"  // 按下效果
        "    border-radius: 3px;"
        "}";

    prevButton->setStyleSheet(transparentStyle);
    playButton->setStyleSheet(transparentStyle);
    nextButton->setStyleSheet(transparentStyle);

    // 去掉焦点框
    prevButton->setFocusPolicy(Qt::NoFocus);
    playButton->setFocusPolicy(Qt::NoFocus);
    nextButton->setFocusPolicy(Qt::NoFocus);

    // 创建主布局
    QGridLayout *mainLayout = new QGridLayout(this);

    // 第一行：图标和歌词
    mainLayout->addWidget(iconLabel, 0, 0, 1, 1);
    mainLayout->addWidget(lyricsLabel, 0, 1, 1, 3);

    // 设置列拉伸比例
    mainLayout->setColumnStretch(0, 1);
    mainLayout->setColumnStretch(1, 4);

    // 第二行：进度条
    mainLayout->addWidget(progressBar, 1, 0, 1, 4);

    // 第三行：按钮居中
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(prevButton);
    buttonLayout->addWidget(playButton);
    buttonLayout->addWidget(nextButton);
    buttonLayout->addStretch();

    mainLayout->addLayout(buttonLayout, 2, 0, 1, 4);

    // 设置紧凑的布局边距和间距
    mainLayout->setContentsMargins(8, 8, 8, 8);
    mainLayout->setVerticalSpacing(8);
    mainLayout->setHorizontalSpacing(8);

    // 固定组件尺寸
    iconLabel->setFixedSize(40, 40);
    lyricsLabel->setFixedHeight(40);

    // 设置窗口属性
    setWindowTitle("音乐播放器");
    setFixedSize(240, 190);
}

void music::setupConnections()
{
    connect(prevButton, &QPushButton::clicked, this, &music::onPrevButtonClicked);
    connect(playButton, &QPushButton::clicked, this, &music::onPlayButtonClicked);
    connect(nextButton, &QPushButton::clicked, this, &music::onNextButtonClicked);
    connect(this, &music::searchRequested, this->network, &music_json::on_pushButton_clicked);
    connect(playTimer, &QTimer::timeout, this, &music::updatePlayback);
    connect(this->network, &music_json::emit_data, this, &music::onDataReceived);
    connect(mediaPlayer, &QMediaPlayer::stateChanged, this, &music::onMediaStateChanged);
    connect(mediaPlayer, &QMediaPlayer::durationChanged, this, &music::onDurationChanged);
}

void music::onDataReceived(QList<int> positions, QStringList lyrics)
{
    qDebug() << "收到歌词数据，时间点数量:" << positions.size() << "歌词数量:" << lyrics.size();

    // 存储接收到的数据
    m_positions = positions;
    m_lyrics = lyrics;

    // 重置播放状态
    currentPosition = 0;
    currentLyricIndex = -1;

    // 计算总时长（最后一个时间点 + 假设的持续时间）
    if (!positions.isEmpty()) {
        totalDuration = positions.last() + 5000;
        progressBar->setRange(0, totalDuration);
        progressBar->setValue(0);
    }

    // 显示第一句歌词（如果有）
    if (!lyrics.isEmpty()) {
        lyricsLabel->setText("准备播放...\n" + lyrics.first());
    } else {
        lyricsLabel->setText("无歌词内容");
    }

    qDebug() << "歌词数据加载完成，总时长:" << totalDuration << "ms";
}

void music::updatePlayback()
{
    if (!isPlaying) return;

    // 获取实际的媒体播放器位置
    currentPosition = mediaPlayer->position();
    qint64 duration = mediaPlayer->duration();

    // 调试输出，帮助诊断问题
    qDebug() << "当前位置:" << currentPosition << "总时长:" << duration;

    // 只有当有有效的时长时才更新进度条
    if (duration > 0) {
        // 计算进度百分比 (0-100)
        int progress = static_cast<int>((currentPosition * 100) / duration);
        progressBar->setValue(progress);

        // 更新时间显示
        QTime currentTime = QTime(0, 0, 0).addMSecs(currentPosition);
        QTime totalTime = QTime(0, 0, 0).addMSecs(duration);
        progressBar->setFormat(QString("%1 / %2").arg(
            currentTime.toString("mm:ss"),
            totalTime.toString("mm:ss")));

        qDebug() << "进度百分比:" << progress << "%";
    } else {
        // 如果没有获取到时长，显示未知状态
        progressBar->setFormat("加载中...");
    }

    // 更新歌词显示
    updateLyricsDisplay(currentPosition);
}
// 添加媒体时长变化的槽函数
void music::onDurationChanged(qint64 duration)
{
    qDebug() << "媒体时长变化:" << duration;

    if (duration > 0) {
        // 重置进度条范围
        progressBar->setRange(0, 100);
        progressBar->setValue(0);

        // 更新总时长
        totalDuration = duration;

        // 设置时间格式
        QTime totalTime = QTime(0, 0, 0).addMSecs(duration);
        progressBar->setFormat(QString("00:00 / %1").arg(totalTime.toString("mm:ss")));
    }
}
void music::updateLyricsDisplay(int currentTime)
{
    if (m_positions.isEmpty() || m_lyrics.isEmpty()) return;

    // 查找当前应该显示的歌词
    int newIndex = -1;
    for (int i = m_positions.size() - 1; i >= 0; --i) {
        if (currentTime >= m_positions[i]) {
            newIndex = i;
            break;
        }
    }

    // 如果找到了新的歌词且与当前显示的不同，则更新显示
    if (newIndex != -1 && newIndex != currentLyricIndex) {
        currentLyricIndex = newIndex;
        lyricsLabel->setText(m_lyrics[newIndex]);
        qDebug() << "切换到歌词:" << newIndex << "时间:" << currentTime << "ms 内容:" << m_lyrics[newIndex];
    }

    // 如果没有找到匹配的歌词（在开始播放前）
    if (newIndex == -1 && currentLyricIndex != -1) {
        currentLyricIndex = -1;
        lyricsLabel->setText("准备播放...");
    }
}

void music::onMediaStateChanged(QMediaPlayer::State state)
{
    // 根据媒体播放器状态更新按钮图标
    if (state == QMediaPlayer::PlayingState) {
        isPlaying = true;
        playButton->setIcon(QIcon(":/停止"));  // 切换到暂停图标
        playTimer->start();  // 开始更新进度
    } else {
        isPlaying = false;
        playButton->setIcon(QIcon(":/开始"));  // 切换到播放图标
        playTimer->stop();   // 停止更新进度
    }
}

void music::onPrevButtonClicked()
{
    // 后退5秒
    qint64 currentPos = mediaPlayer->position();
    if(currentPos <= 5000) {
        mediaPlayer->setPosition(0);
    } else {
        mediaPlayer->setPosition(currentPos - 5000);
    }
}

void music::onPlayButtonClicked()
{
    // 切换播放/暂停状态
    if (mediaPlayer->state() == QMediaPlayer::PlayingState) {
        mediaPlayer->pause();
    } else {
        // 如果播放列表有内容且未开始播放，确保从当前位置开始
        if (mediaPlayer->state() == QMediaPlayer::StoppedState && musiclist->mediaCount() > 0) {
            mediaPlayer->play();
        } else {
            mediaPlayer->play();
        }
    }
}

void music::onNextButtonClicked()
{
    // 前进5秒
    qint64 currentPos = mediaPlayer->position();
    if(currentPos + 5000 >= mediaPlayer->duration()) {
        mediaPlayer->setPosition(mediaPlayer->duration());
    } else {
        mediaPlayer->setPosition(currentPos + 5000);
    }
}

void music::handle_search(QString song)
{
    qDebug() << "搜索歌曲:" << song;

     lyricsLabel->setText("正在加载: " + song);

     // 检查歌曲是否在映射中
     if (songMap.contains(song)) {
         QString songId = songMap[song];
         qDebug() << "找到歌曲ID:" << songId;

         // 构建真正的歌曲URL
         QString url = "http://music.163.com/song/media/outer/url?id=" + songId + ".mp3";
         qDebug() << "构建的歌曲URL:" << url;
         QString url_1 = "http://music.163.com/api/song/lyric?id=" + songId + "&lv=1&kv=1&tv=-1";

         // 请求歌词数据
         emit searchRequested(url_1);

         // 清除当前播放列表
         musiclist->clear();

         // 添加歌曲到播放列表
         musiclist->addMedia(QUrl(url));

         // 设置播放模式为当前项（只播放这一首）
         musiclist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce);

         // 重置播放状态
         isPlaying = false;
         currentPosition = 0;
         currentLyricIndex = -1;
         progressBar->setValue(0);
         progressBar->setFormat("00:00 / --:--"); // 重置显示

         // 尝试预加载媒体以获取时长信息
         mediaPlayer->setPosition(0);

     } else {
         qDebug() << "未找到歌曲:" << song;
         lyricsLabel->setText("未找到歌曲: " + song);
     }
}
